﻿
ko.bindingHandlers.stopBinding = {
    init: function () {
        return { controlsDescendantBindings: true };
    }
};

ko.dirtyFlag = function (root, isDirty) {
    var _propertyArray;

    var getEditableProperties = function () {
        if (_propertyArray == undefined) {
            _propertyArray = [];
            for (var prop in root) {
                // If the property has a required extension method, add it to the include array
                if (root[prop] && root[prop].isTracking && root[prop].isTracking() == true)
                    _propertyArray.push(prop);
            }
        }
        return _propertyArray;
    };

    var getJsonObjectWithValidParametersOnly = function () {
        var copy = ko.toJS(root);
        return JSON.stringify(copy, getEditableProperties());
    };


    var result = function () { };

    var initialState = ko.observable(getJsonObjectWithValidParametersOnly());
    var isInitiallyDirty = ko.observable(isDirty);

    result.isDirty = ko.computed(function() {
        return isInitiallyDirty() || initialState() !== getJsonObjectWithValidParametersOnly();
    });

    result.reset = function () {
        var originalParameters = ko.utils.parseJson(initialState());
        for (var prop in originalParameters) {
            if (root.hasOwnProperty(prop)) {
                var originalValue = originalParameters[prop];
                root[prop](originalValue);
            }
        }
    };

    result.update = function() {
        initialState(getJsonObjectWithValidParametersOnly());
        isInitiallyDirty(false);
    };

    return result;
};

ko.extenders.trackChange = function(target) {
    target.isTracking = ko.observable(true);
};


ko.extenders.trimString = function (target, option) {
    return ko.computed({
        read: function () {
            if (target() == null)
                return null;
            return target().trim();
        },
        write: function (value) {
            if (value == null) {
                target(null);
                return;
            }
            target(value.trim());
            target.valueHasMutated();
        },
        owner: this
    }).extend({ notify: 'always' });
};